package edu.bw.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class ConnectionFactory {

    @Autowired
    ThreadLocal<Connection> threadLocal;

    @Autowired
    DataSource dataSource;

    public Connection currentThreadConn(){
        //1.先尝试从ThreadLocal获取当前线程对应的连接
        Connection connection=threadLocal.get();

        //2.判断当前线程对应的是否有连接
        if (connection ==null){
            try {
                connection=dataSource.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            threadLocal.set(connection);
        }
        return connection;
    }
}
